#include "./draw_task.h"
#include "../driver/sensor.h"
#include "../driver/ctrl.h"
#include "../cfg/app_info.h"

namespace task {

DrawTask drawTask;

using namespace driver;
using namespace cfg;

void DrawTask::run() {

    for (;;) {
        switch (m_state) {
            case State::IDLE: do_idle(); break;
            case State::TIMEOUT: do_timeout(); break;
            case State::STOP: do_stop(); break;
            case State::WORK: do_work(); break;
        }
    }
}

void DrawTask::do_idle() {
    for (;;) {
        if (!sensor.is_water_level_high()) {
            m_state = State::WORK;
            break;
        }
        if (wait(500)) {
            break;
        }
    }
}

void DrawTask::do_work() {
    uint32_t time_count = 0;

    ctrl.open(parts::V1);
    ctrl.open(parts::V3);
    ctrl.open(parts::WATER_PUMP);
    for (;;) {
        if (sensor.is_water_level_high()) {
            m_state = State::IDLE;
            break;
        }
        if (wait(500)) {
            break;
        }
        time_count += 500;
        if (time_count >= appInfo->draw_timeout) {
            m_state = State::TIMEOUT;
            break;
        }
    }
    ctrl.close(parts::V1);
    ctrl.close(parts::V3);
    ctrl.close(parts::WATER_PUMP);
}

void DrawTask::do_timeout() {
    wait();
}

void DrawTask::do_stop() {
    m_flags.set_flags(FLAG_STOP);
    wait();
}



}
